<?php

declare(strict_types=1);

namespace App\Controller;

use App\Helpers\Utils;
use App\Model\Config;
use Hyperf\HttpServer\Annotation\AutoController;
use Qiniu\Auth;

/**
 * @AutoController()
 */
class UploadController extends BaseController
{
    public function getToken()
    {
        $config = Config::where('name','image')->first();
        $config = $config->config;

        $auth = new Auth($config->access_key,$config->secret_key);

        $bucket = $config->bucket;

        // 生成上传Token
        $token = $auth->uploadToken($bucket);

        return $this->success(['token' => $token]);
    }


    //  本地上传,未测试
    public function upload()
    {
        try{
            $file = $this->request->file('image');

            //  获取文件扩展名
            $extension = $file->getExtension();

            $name = Utils::getNumber() . '.' . $extension;

            $path = '/upload/' . '.' . $name;

            $file->moveTo($path);

            // 通过 isMoved(): bool 方法判断方法是否已移动
            if ($file->isMoved()) {
                return $this->success(['path' => $path]);
            }
        }catch (\Exception $exception){
            return $this->failed('上传失败');
        }
    }
}
